import os
from typing import Optional, Dict, List

from fit_py_ask_number_demo.data_managers import sqlite_manager


class RuleManager:
    def __init__(self):
        """
        初始化规则管理器
        """
        db_path = os.path.join(os.path.dirname(__file__), '../../database/kpi2.db')
        self.db_manager = sqlite_manager.SQLiteManager(db_path)
        self.initialize_table()

    def initialize_table(self):
        """
        初始化规则表
        如果表已存在，则跳过初始化
        """
        if not self.db_manager.connection:
            self.db_manager.connect()

        try:
            cursor = self.db_manager.connection.cursor()

            # 检查表是否存在
            cursor.execute('''
            SELECT name FROM sqlite_master WHERE type='table' AND name='rules'
            ''')
            table_exists = cursor.fetchone()

            if table_exists:
                return

            # 创建规则表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS rules (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    rule_name TEXT NOT NULL,
                    rule TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')

            self.db_manager.connection.commit()
            print("rules 表初始化成功！")
        except Exception as e:
            print(f"初始化 rules 表失败: {e}")

    def list_rules(self, page: int, page_size: int, rule_name: str = '', rule: str = '') -> Dict:
        """
        获取规则列表，支持分页和搜索
        :param page: 页码
        :param page_size: 每页数量
        :param rule_name: 搜索规则名称
        :param rule: 搜索规则内容
        :return: 包含分页数据和总数的字典
        """
        # 构建 WHERE 子句
        conditions = []
        if rule_name:
            conditions.append(f"rule_name LIKE '%{rule_name}%'")
        if rule:
            conditions.append(f"rule LIKE '%{rule}%'")
        
        where_clause = " AND ".join(conditions) if conditions else None
        
        # 获取总数
        total_result = self.db_manager.read('rules', where_clause)
        total = len(total_result)
        
        # 获取分页数据
        offset = (page - 1) * page_size
        if where_clause:
            where_clause += f" ORDER BY id DESC LIMIT {page_size} OFFSET {offset}"
        else:
            where_clause = f"1=1 ORDER BY id DESC LIMIT {page_size} OFFSET {offset}"
            
        items = self.db_manager.read('rules', where_clause)
        
        return {
            'total': total,
            'items': items
        }

    def add_rule(self, rule_name: str, rule: str) -> bool:
        """
        添加新的规则
        :param rule_name: 规则名称
        :param rule: 规则内容
        :return: 是否成功
        """
        data = {
            'rule_name': rule_name,
            'rule': rule
        }
        return self.db_manager.create('rules', data)

    def update_rule(self, rule_id: int, rule_name: str, rule: str) -> bool:
        """
        更新规则
        :param rule_id: 规则ID
        :param rule_name: 新的规则名称
        :param rule: 新的规则内容
        :return: 是否成功
        """
        data = {
            'rule_name': rule_name,
            'rule': rule
        }
        return self.db_manager.update('rules', data, f"id = {rule_id}")

    def delete_rule(self, rule_id: int) -> bool:
        """
        删除规则
        :param rule_id: 规则ID
        :return: 是否成功
        """
        return self.db_manager.delete('rules', f"id = {rule_id}")

    def get_rule(self, rule_id: int) -> Optional[Dict]:
        """
        获取单个规则
        :param rule_id: 规则ID
        :return: 规则信息，如果未找到则返回 None
        """
        result = self.db_manager.read('rules', f"id = {rule_id}")
        return result[0] if result else None

    def get_rule_by_name(self, rule_name: str) -> Optional[Dict]:
        """
        根据规则名称获取规则
        :param rule_name: 规则名称
        :return: 规则信息，如果未找到则返回 None
        """
        result = self.db_manager.read('rules', f"rule_name = '{rule_name}'")
        return result[0] if result else None 